package com.xipu.yygh.order.controller;

import com.xipu.yygh.common.exception.YyghException;
import com.xipu.yygh.common.result.R;
import com.xipu.yygh.enums.PaymentTypeEnum;
import com.xipu.yygh.order.service.PaymentInfoService;
import com.xipu.yygh.order.service.WeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * description: 微信支付Controller
 * @author: gql
 * @date: 2022/05
 */
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
    /**
     * 微信支付Service
     */
    @Autowired
    private WeixinService weixinPayService;

    /**
     * 支付信息Service
     */
    @Autowired
    private PaymentInfoService paymentInfoService;

    /**
     * 生成二维码
     * @param orderId 订单Id
     * @return r
     */
    @GetMapping("/createNative/{orderId}")
    public R createNative(@PathVariable("orderId") Long orderId) {
        Map map = this.weixinPayService.createNative(orderId);
        return R.ok().data(map);
    }

    /**
     * 查询支付状态
     * @param orderId 订单Id
     * @return r
     */
    @GetMapping("/queryPayStatus/{orderId}")
    public R queryPayStatus(@PathVariable("orderId") Long orderId) {
        // 1.查询微信接口,查看支付状态
        Map<String, String> resultMap = this.weixinPayService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.name());
        // 2.如果支付状态为空,返回支付失败
        if (CollectionUtils.isEmpty(resultMap)) {
            throw new YyghException(20001, "支付失败");
        }
        // 3.如果支付成功,更新订单状态和支付状态为成功
        String success = "SUCCESS";
        String tradeState = "trade_state";
        if (success.equals(resultMap.get(tradeState))) {
            // 更新两个状态
            this.paymentInfoService.paySuccess(resultMap.get("out_trade_no"), PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
            return R.ok().message("支付成功");
        }
        // 4.否则表明网络波动,显示支付中
        return R.ok().message("支付中");
    }
}
